import PateoTable from '@/common/PateoTable/PateoTable';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import { getDicByKey, getDictOptionsByCode } from '@/support/common';
import { Card, Form } from 'antd';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import router from 'umi/router';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import Ellipsis from '../../../components/Ellipsis';
import BaseUserDetailModal from './baseUserDetailModel';
import styles from './TableList.less';
import ResetPwdModel from './UserResetPwdModel';

let page = '';
const FormItem = Form.Item;
@connect(state => ({
  baseUser: state.baseUser,
}))
// @Form.create()
export default class BaseUserList extends PureComponent {
  static contextTypes = {
    authButton: PropTypes.array,
    dicData: PropTypes.any,
  };
  state = {
    baseUserDetailVisible: false,
    baseUserDetailModelData: {},
    vehicleDetailModelData: {},
    formValues: {},
    accountType: '',
  };

  formRef = React.createRef();

  componentWillMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'baseUser/clearData',
      payload: {},
    });
    // if (this.props.location && this.props.location.state) {
    //   const { query } = this.props.location.state;
    //   const { pageObj, values } = query;
    //   this.setState({ formValues: values });
    //   dispatch({
    //     type: 'baseUser/fetch',
    //     payload: {
    //       page: pageObj.current - 1,
    //       size: pageObj.pageSize,
    //       ...values,
    //     },
    //   });
    // }
    // else {
    //   dispatch({
    //     type: 'baseUser/fetch',
    //   });
    // }
  }
  componentDidMount() {
    if (this.state.formValues) {
      this.formRef.current.setFieldsValue({
        userName: this.state.formValues.userName,
        mobilePhone: this.state.formValues.mobilePhone,
        idType: this.state.formValues.idType,
        idNo: this.state.formValues.idNo,
      });
    }
  }
  handleFormReset = () => {
    const { dispatch } = this.props;
    this.formRef.current.resetFields();
    this.state.formValues = {};
    dispatch({
      type: 'baseUser/clearData',
      payload: {},
    });
  };

  handleEditDate = sid => {
    const { dispatch } = this.props;
    const obj = {};
    obj.pageObj = page;
    obj.values = this.state.formValues;
    dispatch({
      type: 'baseUser/fetchBaseUserBySid',
      payload: sid,
      callback: res => {
        const { data } = res;
        router.push({
          pathname: '/baseUserManager/baseUser/baseUserEdit',
          flag: true,
          state: { data, obj },
        });
      },
    });
  };
  onRef = ref => {
    this.resetPwdModel = ref;
  };
  resetPsw = userAccountSid => {
    this.resetPwdModel.showModal(userAccountSid);
  };

  linkToBindVehicle = record => {
    const { dispatch } = this.props;
    const obj = {};
    obj.pageObj = page;
    obj.values = this.state.formValues;
    dispatch({
      type: 'baseUser/fetchVehicleByUserAccountSid',
      payload: record.userAccountSid,
      callback: data => {
        router.push({
          pathname: '/baseUserManager/baseUser/baseUserBind',
          flag: true,
          state: { data, obj, record },
        });
      },
    });
  };

  handleSearch = fieldsValue => {
    this.setState({
      formValues: fieldsValue,
    });
    this.props.dispatch({
      type: 'baseUser/fetch',
      payload: fieldsValue,
    });
  };
  handleDetailBaseUser = (sid, userAccountSid, accountType) => {
    this.setState({ accountType });
    const { dispatch } = this.props;
    dispatch({
      type: 'baseUser/fetchVehicleByUserAccountSid',
      payload: userAccountSid,
      callback: data => {
        this.setState({ vehicleDetailModelData: data });
      },
    }).then(
      dispatch({
        type: 'baseUser/fetchBaseUserBySid',
        payload: sid,
        callback: data => {
          this.setState({ baseUserDetailModelData: data.data, baseUserDetailVisible: true });
        },
      }),
    );
  };

  renderForm() {
    const certType = getDictOptionsByCode(this.context.dicData, 'certType');
    const colStyle = { paddingLeft: 0, paddingTop: 10 };
    // const { getFieldDecorator } = this.props.form;
    const searchItems = [
      {
        title: '用户名',
        type: 'input',
        key: 'userName',
        render: val => (
          <Ellipsis length={10} tooltip>
            {val}
          </Ellipsis>
        ),
      },
      {
        title: '手机号',
        type: 'input',
        key: 'mobilePhone',
      },
      {
        title: '证件类型',
        type: 'select',
        selectOptions: certType,
        key: 'idType',
      },
      {
        title: '证件号',
        type: 'input',
        key: 'idNo',
        render: val => (
          <Ellipsis length={18} tooltip>
            {val}
          </Ellipsis>
        ),
      },
    ];
    return (
      // <Form onFinish={this.handleSearch} layout="inline" ref={this.formRef}>
      //   <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
      //     <Col md={8} sm={24}>
      //       <FormItem label="用&nbsp;&nbsp;户&nbsp;&nbsp;名" name="userName">
      //         <Input placeholder="请输入用户名" />
      //       </FormItem>
      //     </Col>
      //     <Col md={8} sm={24}>
      //       <FormItem label="手机号" name="mobilePhone" rules={[{
      //         required: true, message: '请输入手机号',
      //       }]}>
      //         <Input placeholder="请输入手机号" maxLength={11} />
      //       </FormItem>
      //     </Col>
      //     <Col md={8} sm={24}>
      //       <FormItem label="证件类型" name="idType">
      //         <Select placeholder="请选择" allowClear options={certType} />
      //       </FormItem>
      //     </Col>
      //     <Col md={8} sm={24}>
      //       <FormItem label="证件号" name="idNo">
      //         <Input placeholder="请输入证件号" />
      //       </FormItem>
      //     </Col>
      //     <Col  md={16} sm={24}>
      //       <Row justify='end' className={styles.submitButtons}>
      //         <Button type="primary" htmlType="submit" onClick={() => this.formRef.current.submit()}>查询</Button>
      //         <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
      //       </Row>
      //     </Col>
      //   </Row>
      //   {/* <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
      //     <Col md={8} sm={24}>
      //       <FormItem label="证件号" name="idNo">
      //         <Input placeholder="请输入证件号" />
      //       </FormItem>
      //     </Col>
      //     <Col md={4} sm={24} style={{ float: 'right' }} >
      //       <span className={styles.submitButtons}>
      //         <Button type="primary" htmlType="submit" onClick={() => this.formRef.current.submit()}>查询</Button>
      //         <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
      //       </span>
      //     </Col>
      //   </Row> */}
      // </Form>

      <Card bordered={false}>
        <PateoSearchForm
          searchItems={searchItems}
          onRef={ref => (this.formRef = ref)}
          fetchParams={{ type: 'baseUser/fetch' }}
          saveFormValues={val =>
            this.setState({ formValues: Object.assign(this.state.formValues, val) })
          }
          handleFormReset={() => this.setState({ formValues: {} })}
        />
      </Card>
    );
  }

  render() {
    const isAuth = true; // this.context.authButton.includes('baseUser-opt');

    const {
      baseUser: {
        loading,
        baseUserData: { list, pagination },
      },
      dispatch,
      location: { pathname = '/' },
    } = this.props;
    page = pagination;
    const columns = [
      {
        title: '账户ID',
        dataIndex: 'userAccountSid',
        render: (text, record) => {
          return <a onClick={() => this.linkToBindVehicle(record)}>{text}</a>;
        },
      },
      {
        title: '用户名',
        dataIndex: 'userName',
        render: val => (
          <Ellipsis length={10} tooltip>
            {val}
          </Ellipsis>
        ),
      },
      {
        title: '性别',
        dataIndex: 'sexuality',
        render: text => {
          return getDicByKey(this.context.dicData, `sex`, text + '');
        },
      },
      {
        title: '证件类型',
        dataIndex: 'idType',
        render: text => {
          if (text == 0) {
            return '';
          }
          return getDicByKey(this.context.dicData, `certType`, text + '');
        },
      },
      {
        title: '证件号',
        dataIndex: 'idNo',
        render: val => (
          <Ellipsis length={18} tooltip>
            {val}
          </Ellipsis>
        ),
      },
      {
        title: '手机号',
        dataIndex: 'mobilePhone',
      },
      {
        title: '入库时间',
        dataIndex: 'createDate',
      },
      {
        title: '名下车联网类型',
        dataIndex: 'spt',
      },
      {
        title: '操作',
        dataIndex: '操作',
        render: (text, record) => {
          const btns = [
            {
              title: '编辑',
              key: 'edit',
              auth: 'baseUser-opt',
              onConfirm: () => this.handleEditDate.bind(this)(record.sid),
            },
            {
              title: '重置密码',
              key: 'resetPws',
              message: '确定要重置该用户的账户密码吗？',
              Popconfirm: true,
              auth: 'baseUser-opt',
              onConfirm: () => this.resetPsw.bind(this)(record.userAccountSid),
            },
          ];
          return <PateoAuthButtons pathname={pathname} authStr="baseUser-opt" btns={btns} />;
        },
      },
    ];

    const paginationProps = {
      pageSizeOptions: ['10', '20', '50'],
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      columns, // 列
      rowKey: record => record.sid, // key
      loading, // 控制加载
      // bordered: true, // 边框
      selectedRows: [],
      dataSource: list, // 远程数据
      pagination: paginationProps, // 分页
    };
    return (
      <PageHeaderLayout>
        {/* <Card bordered={false}> */}
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          {/*<div className={styles.tableListOperator}>*/}
          {/*{isAuth ? <Button icon="plus" type="primary" onClick={() => this.props.history.push('/baseUserManager/baseUserAdd')}>新增</Button> : ''}*/}
          {/*</div>*/}
          <Card style={{ marginTop: 12 }}>
            <PateoTable
              tableProps={tableProps}
              dispatch={dispatch}
              fetchUrl="baseUser/fetch"
              formValues={this.state.formValues}
            />
          </Card>
          <BaseUserDetailModal
            changeVisible={() =>
              this.setState({
                baseUserDetailVisible: false,
                baseUserDetailModelData: {},
                accountType: '',
                vehicleDetailModelData: {},
              })
            }
            visible={this.state.baseUserDetailVisible}
            detailModelData={this.state.baseUserDetailModelData}
            vehicleDetailModelData={this.state.vehicleDetailModelData}
            accountType={this.state.accountType}
            dispatch={dispatch}
          />
          <ResetPwdModel
            onRef={this.onRef}
            icon="plus"
            type="primary"
            dispatch={this.props.dispatch}
          />
        </div>
        {/* </Card> */}
      </PageHeaderLayout>
    );
  }
}
